package com.iwinding.ladygg.ui.act;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.iwinding.ladygg.R;
import com.iwinding.ladygg.net.response.UserRp;
import com.iwinding.ladygg.runtimepermissions.PermissionsManager;
import com.iwinding.ladygg.runtimepermissions.PermissionsResultAction;
import com.iwinding.ladygg.ui.act.device.DeviceActivity;
import com.iwinding.ladygg.ui.adapter.InvitationAdapter;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;

import main.java.com.lwz.widget.searchbar.SearchBarView;

/**
 * Created by hezhiyong on 2017/4/6.
 */

public class SysContactsActivity extends BaseActivity {
//    我正在使用iCane, 关心身边老人，从我做起。下载: http://www.i-winding.com

    private static final String TAG = DeviceActivity.class.getSimpleName();

    public static final int REQUESTPERMISSION = 1;

    private static final String[] PHONES_PROJECTION = new String[]{
            Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID};

    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;


    private SearchBarView mSearchBarView;
    private ListView mListView;
    private InvitationAdapter adpater;

    private List<UserRp> userRps = new ArrayList<UserRp>();
    private String queryContent = "";

    private List<UserRp> contacts = new ArrayList<UserRp>();

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        if (requestCode == REQUESTPERMISSION) {
//            Log.i(TAG, "onRequestPermissionsResult: permissions.length = " + permissions.length +
//                    ", grantResults.length = " + grantResults.length);
//            if (grantResults.length > 0
//                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                // permission was granted, yay! Do the
//                // contacts-related task you need to do.
//            } else {
//                // permission denied, boo! Disable the
//                // functionality that depends on this permission.
////                Toast.makeText(this, "位置访问权限被拒绝将无法搜索到ble设备", Toast.LENGTH_SHORT).show();
//                Toast.makeText(this, "通讯录权限被拒绝将无法读取通讯录", Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        verifyIfRequestPermission();
    }

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_search_friends;
    }

    void initView() {
        setTitleResId(R.string.icane_add_friends);
//邀请消息内容
//        我正在使用iCane, 关心身边老人，从我做起。下载: http://www.i-winding.com

        mSearchBarView = (SearchBarView) findViewById(R.id.search);
        mListView = (ListView) findViewById(R.id.pullListview);

        adpater = new InvitationAdapter(this, userRps);
        mListView.setAdapter(adpater);

        mSearchBarView.setHintText(getString(R.string.icane_contacts_search_hint));
        mSearchBarView.setOnSearchBarStateChnagedListener(
                new SearchBarView.SimpleSearchBarStateChangedListener() {

                    @Override
                    public boolean onSearchEvent(EditText searchEdit) {
                        queryContent = searchEdit.getEditableText().toString();
                        contactFilter(queryContent);
                        return super.onSearchEvent(searchEdit);
                    }

                    @Override
                    public void onPrepareSearch(EditText searchEidt) {
                    }

                    @Override
                    public void onCancel(EditText searchEidt) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {
                        queryContent = s.toString();
                        if (TextUtils.isEmpty(queryContent)) {

                        }
//                        onPullDownToRefresh(mListView);
                    }

                });
    }


    /**
     * 匹配
     *
     * @param str
     */
    private void contactFilter(String str) {
        List<UserRp> userRpsTemp = new ArrayList<UserRp>();
        for (UserRp userRp : contacts) {
            int indexOfnick = TextUtils.indexOf(userRp.nickName,str);
            int indexOfuname = TextUtils.indexOf(userRp.uname,str);
            int indexOfmobile = TextUtils.indexOf(userRp.mobile,str);
            if (indexOfnick != -1 || indexOfmobile != -1 || indexOfuname!=-1) {
                userRpsTemp.add(userRp);
            }
        }
        if (userRpsTemp.size() != 0) {
            userRps.clear();
            userRps.addAll(userRpsTemp);
        }
        adpater.notifyDataSetChanged();
    }

    /**
     * 初始化联系人
     */
    private void initContacts() {
        contacts.clear();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                getPhoneContacts();
                getSIMContacts();
                myHandler.sendEmptyMessage(0);
            }
        });
        thread.start();
    }

    private void verifyIfRequestPermission() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,new String[]{android.Manifest.permission.READ_CONTACTS}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                initContacts();
            }

            @Override
            public void onDenied(String permission) {
                Toast.makeText(mContext, "只有允许访问通讯录才能调用通讯录", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS)
//                    != PackageManager.PERMISSION_GRANTED) {
//                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
//                        Manifest.permission.READ_CONTACTS)) {
//                    Log.i(TAG, "*********onCreate: shouldShowRequestPermissionRationale**********");
//                    Toast.makeText(this, "只有允许访问通讯录才能调用通讯录", Toast.LENGTH_SHORT).show();
//                } else {
//                    //申请权限  第二个参数是一个 数组 说明可以同时申请多个权限
//                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, REQUESTPERMISSION);
//                }
//            } else {//已授权
//                initContacts();
//            }
//        } else {
//            initContacts();
//        }
    }

    /**
     * 得到手机通讯录联系人信息
     **/
    private void getPhoneContacts() {
        ContentResolver resolver = mContext.getContentResolver();

// 获取手机联系人
        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);

        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;

                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);

                //得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

                //得到联系人头像ID
                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);

//                //得到联系人头像Bitamp
//                Bitmap contactPhoto = null;
//                //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
//                if (photoid > 0) {
//                    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
//                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
//                    contactPhoto = BitmapFactory.decodeStream(input);
//                } else {
//                    contactPhoto = BitmapFactory.decodeResource(getResources(), R.mipmap.user_phone);
//                }
                //得到联系人头像Bitamp
                Uri contactPhoto = null;
                //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                if (photoid > 0) {
                    contactPhoto = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
                } else {
                    contactPhoto = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                            + getResources().getResourcePackageName(R.mipmap.user_phone) + "/"
                            + getResources().getResourceTypeName(R.mipmap.user_phone) + "/"
                            + getResources().getResourceEntryName(R.mipmap.user_phone));
                }

                UserRp userRp = new UserRp();
                userRp.nickName = contactName;
                userRp.mobile = phoneNumber;
                userRp.headImg = contactPhoto.toString();
                contacts.add(userRp);
            }

            phoneCursor.close();
        }
    }

    /**
     * 得到手机SIM卡联系人人信息
     **/
    private void getSIMContacts() {
        ContentResolver resolver = this.getContentResolver();
        // 获取Sims卡联系人
        Uri uri = Uri.parse("content://icc/adn");
        Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
                null);

        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor
                        .getString(PHONES_DISPLAY_NAME_INDEX);

                //Sim卡中没有联系人头像
                UserRp userRp = new UserRp();
                userRp.nickName = contactName;
                userRp.mobile = phoneNumber;
                contacts.add(userRp);
            }

            phoneCursor.close();
        }
    }


    Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (contacts.size() != 0) {
                    userRps.clear();
                    userRps.addAll(contacts);
                }
                adpater.notifyDataSetChanged();
            }
        }
    };

}
